import React, { useState, useEffect } from "react";
import {
  Box,
  Typography,
  Card,
  CardContent,
  Grid,
  Button,
  List,
  ListItem,
  ListItemButton,
  ListItemText,
  Paper,
  Stack,
  CssBaseline,
  ThemeProvider,
} from "@mui/material";
import AddIcon from "@mui/icons-material/Add";
import ReactECharts from "echarts-for-react";
import theme from "../themes/theme ";
import { useNavigate } from "react-router-dom";

interface Survey {
  id: number;
  title: string;
  createdAt: string;
}

const SurveyStatistics: React.FC = () => {
  const navigate = useNavigate();

  const [surveys, setSurveys] = useState<Survey[]>([]);
  const [selectedSurvey, setSelectedSurvey] = useState<Survey | null>(null);

  // 加载本地问卷列表
  useEffect(() => {
    const stored = localStorage.getItem("surveys");
    if (stored) {
      const parsed: Survey[] = JSON.parse(stored);
      setSurveys(parsed);
      if (parsed.length > 0) {
        setSelectedSurvey(parsed[0]);
      }
    }
  }, []);

  // 新增问卷按钮
  const enterSurvey = () => {
    navigate("/newSurvey");
  };

  // 参加问卷按钮
  const enterAnswerSurvey = () => {
    if (!selectedSurvey) {
      alert("请先选择一个问卷");
      return;
    }
    navigate(`/answerSurvey?id=${selectedSurvey.id}`);
  };

  // 饼图配置，标题跟选中问卷同步
  const pieChartOptions = {
    title: {
      text: selectedSurvey ? selectedSurvey.title : "请选择问卷",
      left: "center",
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      bottom: "0%",
    },
    series: [
      {
        name: "满意度",
        type: "pie",
        radius: "50%",
        data: [
          { value: 50, name: "非常满意" },
          { value: 40, name: "满意" },
          { value: 20, name: "一般" },
          { value: 8, name: "不满意" },
          { value: 2, name: "非常不满意" },
        ],
      },
    ],
  };

  // 柱状图配置，标题跟选中问卷同步
  const barChartOptions = {
    title: {
      text: selectedSurvey
        ? `${selectedSurvey.title}（1-5分）`
        : "请选择问卷",
      left: "center",
    },
    xAxis: {
      type: "category",
      data: ["1分", "2分", "3分", "4分", "5分"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: [5, 10, 20, 45, 40],
        type: "bar",
        barWidth: "50%",
        itemStyle: {
          color: "#4FC3F7",
        },
      },
    ],
  };

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Box p={4}>
        <Typography variant="h4" gutterBottom>
          问卷列表
        </Typography>

        <Stack direction="row" spacing={2} mb={2}>
          <Button variant="contained" startIcon={<AddIcon />} onClick={enterSurvey}>
            新增问卷
          </Button>
          <Button
            variant="outlined"
            startIcon={<AddIcon />}
            color="secondary"
            onClick={enterAnswerSurvey}
          >
            参加问卷
          </Button>
        </Stack>

        <Paper variant="outlined">
          <List>
            {surveys.map((survey) => (
              <ListItem disablePadding key={survey.id}>
                <ListItemButton
                  selected={selectedSurvey?.id === survey.id}
                  onClick={() => setSelectedSurvey(survey)}
                >
                  <ListItemText
                    primary={survey.title}
                    secondary={`创建于 ${survey.createdAt}`}
                  />
                </ListItemButton>
              </ListItem>
            ))}
          </List>
        </Paper>
      </Box>

      <Box p={4}>
        <Typography variant="h4" gutterBottom>
          问卷统计分析
        </Typography>

        <Grid container spacing={2} mb={2}>
          <Grid item xs={6}>
            <Card>
              <CardContent>
                <Typography variant="h6">总答卷数</Typography>
                <Typography variant="h4" color="primary">
                  120
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={6}>
            <Card>
              <CardContent>
                <Typography variant="h6">平均评分</Typography>
                <Typography variant="h4" color="secondary">
                  4.2
                </Typography>
              </CardContent>
            </Card>
          </Grid>
        </Grid>

        <Box mt={4}>
          <ReactECharts option={pieChartOptions} style={{ height: 400 }} />
        </Box>

        <Box mt={4}>
          <ReactECharts option={barChartOptions} style={{ height: 400 }} />
        </Box>
      </Box>
    </ThemeProvider>
  );
};

export default SurveyStatistics;
